<?php

namespace App\Http\Controllers;

use App\Channel;
use App\News;
use Illuminate\Http\Request;
use MercurySeries\Flashy\Flashy;

class NewsController extends Controller
{
    public function show(Request $request)
    {
        $channels = Channel::where('type',1)->get();

        $news = News::when($request->name ,function ($query) use($request){
            return $query->where('title' ,'like' ,'%'.$request->name.'%');
        })->when($request->channel ,function ($query) use($request){
            return $query->where('channel_id' ,$request->channel);
        })->where('is_post' ,1)->with('channel')->orderBy('id','DESC')->paginate(15);

        return view('news.show' ,compact('news','channels','request'));
    }

    public function add()
    {
        $channels = Channel::where('type',1)->get();
        return view('news.add' ,compact('channels'));
    }

    public function store(Request $request)
    {

        News::create( $request->all() );

        Flashy::success('发布成功');

        return redirect()->back();
    }

    public function edit(News $news)
    {
        $channels = Channel::where('type',1)->get();
        return view('news.edit' ,compact('news','channels'));
    }

    public function update(News $news ,Request $request)
    {
        $news->update($request->all());

        Flashy::success('修改成功');

        return redirect()->back();
    }

    public function kenny()
    {
        dd('kenny');
    }

    public function delete(News $news)
    {
        $news->delete();

        Flashy::success('操作成功');

        return redirect()->back();
    }
}
